/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bitzer.google;

import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.client.calendar.CalendarQuery;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.Person;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.extensions.When;
import com.google.gdata.data.extensions.Where;
import com.google.gdata.util.AuthenticationException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author fstech
 */

public class Calendar {

    private static Calendar _instance = null;
    private final CalendarService service;
    public int  recordCount = 0;
    public Calendar() {
        service = new CalendarService(Constants.APPLICATION_NAME);
    }

    public static Calendar instance() {
        if (_instance == null) {
            _instance = new Calendar();
        }
        return _instance;
    }

    public void authenticate(String username, String password) throws AuthenticationException {

        if (username == null || password == null) {
            return;
        }
        service.setUserCredentials(username, password);
    }

    public CalendarEventFeed getFeed(String lastModifiedOn, int startIndex, int numberOfRows , HttpServletRequest request) {

    try {
            URL feedUrl = new URL(Constants.CALENDAR_FEED_URL);
            CalendarQuery calQuery = new CalendarQuery(feedUrl);

            calQuery    = setQueryParameters(calQuery , request);
            
            calQuery.setStartIndex(startIndex);
            calQuery.setMaxResults(numberOfRows);
            CalendarEventFeed feed = service.query(calQuery, CalendarEventFeed.class);
            recordCount =   feed.getEntries().size();
            return feed;
        } catch (Exception e) {
            return null;
        }
    }

     public static CalendarQuery setSortParameters(CalendarQuery query,HttpServletRequest request){

        String queryString = request.getQueryString();

        ArrayList sortColumns = Utils.getParams(queryString, "sortByColumn");
        ArrayList sortByOrder = Utils.getParams(queryString, "sortByOrder");

        if (!sortColumns.isEmpty()) {
            query.setStringCustomParameter("orderby","starttime");
        }
        if(!sortByOrder.isEmpty()){
            String order = (String)sortByOrder.get(0);
            if(order.equals("DESC")){
                query.setStringCustomParameter("sortorder","descending");
            }
            else{
                query.setStringCustomParameter("sortorder","ascending");
            }
        }else{
             query.setStringCustomParameter("sortorder","ascending");
        }
        return query;
    }


     
    public static CalendarQuery setQueryParameters(CalendarQuery query, HttpServletRequest request) {

        query = setSortParameters(query, request);
        query = setSearchParameters(query,request);
        return query;
    }

    public static CalendarQuery setSearchParameters(CalendarQuery query,HttpServletRequest request){

        String queryString = request.getQueryString();
        ArrayList searchColumns = Utils.getParams(queryString, "searchColumn");
        DateFormat bitzerFormat = new SimpleDateFormat(Constants.BITZER_DATE_FORMAT);
        DateTime startTime = null;
        DateTime endTime    = null;
        
        if(!searchColumns.isEmpty()){
            ArrayList searchValues = Utils.getParams(queryString, "searchValue");
            if(searchColumns.size() == searchValues.size()){
                for(int i = 0; i<searchColumns.size();i++){
                        
                    if (searchColumns.get(i).equals("starttime")) {
                        try {
                            Date startDate = bitzerFormat.parse(URLDecoder.decode((String) searchValues.get(i),"UTF-8"));
                            startTime  = new DateTime(startDate.getTime());
                        } catch (Exception e) {

                        }
                    }
                    else if(searchColumns.get(i).equals("endtime"))
                    {
                      try {
                            Date endDate = bitzerFormat.parse(URLDecoder.decode((String) searchValues.get(i),"UTF-8"));
                            endTime  = new DateTime(endDate.getTime());

                        } catch (Exception e) {

                        }
                    }else{
                        query.setFullTextQuery((String)searchValues.get(i));
                    }
                }
            }
        }
 
        if (startTime == null) {
            startTime = DateTime.now();
            query.setMinimumStartTime(startTime);
        }else{
            query.setMinimumStartTime(startTime);
        }

        if (endTime == null) {
            endTime = new DateTime(DateTime.now().getValue() + Long.parseLong("31536000000"));
            query.setMaximumStartTime(endTime);
        }else{
            query.setMaximumStartTime(endTime);
        }

        
 
        return query;
    }
      
    public static void main(String args[]) throws Exception {

        URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full");

        CalendarQuery myQuery = new CalendarQuery(feedUrl);

        CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
        myService.setUserCredentials("mvl.test.gdata@gmail.com", "gdata123");

        
        CalendarEventEntry entry = null;
        List<Person> author = null;
        List<Where> location = null;
        List<When> when      = null;
        int j                = 0;
        // myQuery.setFullTextQuery("Arasu");
        // Send the request and receive the response:
        
        CalendarEventFeed resultFeed = myService.query(myQuery, CalendarEventFeed.class);
        for (int i = 0; i < resultFeed.getEntries().size(); i++) {
            entry = (CalendarEventEntry)resultFeed.getEntries().get(i);

            System.out.println(entry.getTitle().getPlainText());
            when = entry.getTimes();
            if(!when.isEmpty()){
               System.out.println(when.get(0).getStartTime());
               System.out.println(Utils.formattedDateTime(when.get(0).getStartTime()));
               System.exit(0);
            }

        }
    }
}
